import { useCallback, useContext, useMemo, useState } from "react";
import { Button, Image, Toast } from "antd-mobile";

import { login } from "@/api/login";
import FormInput from "@/components/Input";
import styles from "./index.module.less";
import { useHandle } from "@/utils/hooks";
import { sha1 } from "@/utils";
import { AppContext } from "@/context";
import { useHistory, useLocation } from "react-router-dom";
import React from "react";

const number = "95000012";

const Login = () => {
  const params = useLocation();

  const routeParams = useMemo(() => {
    const path = params.search.slice(1).split("&")?.[0].split("=")?.[1];
    if (path) {
      return `${path}`;
    } else {
      return `/statistics`;
    }
  }, [params]);

  const [phone, setPhone] = useState("17710000010");
  const [password, setPassword] = useState("000010");
  const history = useHistory();

  const { data, dispatch } = useContext(AppContext);

  const { load, loading } = useHandle(
    // login,
    (params: any) =>
      Promise.resolve({
        is_leader: 1,
        department_name: "好部门",
      }),
    useCallback(
      (res) => {
        Toast.show({
          icon: "success",
          content: "登录成功",
        });
        dispatch({
          type: "user",
          payload: res,
        });
        history.replace(routeParams);
      },
      [routeParams]
    ),

    useCallback((err: any) => {
      console.log(err);
    }, [])
  );

  const handle = useCallback(() => {
    const pwd = sha1(
      `9823"rhdAGF3'4T>%$@gadgu8@324${password}ASosrg89025r'ng^&@12-"~!$^%sbvuofsd${phone}`
    );
    load({
      phone: phone,
      password: pwd,
      number: number,
    });
  }, [phone, password]);

  return (
    <div className={styles.container}>
      <Image className={styles.img} />
      <span className={styles.title}>渠道商客户系统</span>
      <FormInput
        outerClassnames={styles.form_input}
        placeholder="输入手机号"
        value={phone}
        onChange={(value) => {
          setPhone(value);
        }}
        maxLength={11}
      />
      <FormInput
        placeholder="输入密码"
        type="password"
        value={password}
        onChange={(val) => {
          setPassword(val);
        }}
      />
      <Button
        color="primary"
        onClick={() => {
          handle();
        }}
        className={styles.btn}
        loading={loading}
        // disabled
      >
        登录
      </Button>
      <span className={styles.text}>忘记密码</span>
    </div>
  );
};

export default Login;
